package com.michael.demos.springboot.openapi;

import com.sun.javafx.binding.StringFormatter;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 类功能描述:
 * <pre>
 *   创造最终访问API的链接地址信息
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2020/11/27 14:13
 */
public class MakeData {

    /***
     *
     #  "appKey": "0WBMDu",
     #  "appSecret": "djkkdT",
     #  "secretKey":
     3yblKgZ1y33foxnNXRyG5UqFVhmChyRMTFCB2bDFKQdbZ3mTpv6p1xNOKP9pBZOkio5Q42I73XR5PSrt4FCw2JNF08bYxA7nwnOlHajMJcciVIKHJXZJfOjUF1A91krc"
     #  "token": "WvcqgpGPuGZUu9t0BpAlvwrko66AFpL6dpqakl2nBIYZmAs6NFgO4AxUF0fPZu3P"
     */

    public static void main(String[] args) throws Exception {

        String name = "abc";
        String timestamp = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli() + "";
        String nonce = "ASDEFGg";
        String token = "MUlnPTOLWtMku3PBJSWi8Z3UE3AId0qg8h60rx2qNPhVMkh4NXyJidUQdd4ntsvB";

        String secretKey =
                "3ceBvod4coWZkzPcESPwy7rZPsQRibXNSKRvEk5tg2wezzxHashbUGY9qbx5YoNCuTp3L5pagOnYnvN3y0h0opQ0q7Ful88FuX2Rh9phwhr0JssqbYnPjcCbeIKzgTWN";

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("name", name);
        paramMap.put("timestamp", timestamp);
        paramMap.put("nonce", nonce);
        paramMap.put("token", token);

        String sign = getSign(paramMap, secretKey);

        System.out.println(sign);
        String resultUrl = StringFormatter
                .format("http://127.0.0.1:8080/open-api/a?name=%s&timestamp=%s&nonce=%s&token=%s&sign=%s", name,
                        timestamp, nonce, token, sign
                ).getValue();
        System.out.println(resultUrl);

    }

    /** 签名检验 */
    private static String getSign(Map<String, String> paramMap, String secretKey) throws Exception {

        Set<String> keySet = paramMap.keySet();
        String[] keyArray = keySet.toArray(new String[0]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals("sign")) {
                continue;
            }
            if (paramMap.get(k).trim().length() > 0) {
                // 参数值为空，则不参与签名
                sb.append(k).append("=").append(paramMap.get(k).trim()).append("&");
            }
        }
        sb.append("key=").append(secretKey);

        return sha256(sb.toString(), secretKey);
    }


    public static String sha256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8));

        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
        }
        return sb.toString().toUpperCase();
    }
}
